import 'dart:async';

import 'package:rxdart/rxdart.dart';

import 'SocketClient.dart';

///管理多个socket连接，ip+port作为client的唯一识别，
///并提供统一的接口回调，支持链接状态监听，数据接收监听，数据发送，断开连接等操作。

class SocketClientManager {
  SocketClientManager();

  final Map<String, SocketClient> clients = {};

  /// 数据接收流
  final dataStream = BehaviorSubject<MapEntry<int, String>>();
  final Map<String, StreamSubscription<String>> _dataSubscriptions = {};

  /// 连接状态流
  final connectionStateStream = BehaviorSubject<MapEntry<String, bool>>();
  final Map<String, StreamSubscription<bool>> _subscriptions = {};

  // 添加客户端
  void addClient(String pzIPv4, int uPort) {
    final key = '$pzIPv4:$uPort';
    print('[addSocketClient] ------> $key');
    if (!clients.containsKey(key)) {
      final client = SocketClient(host: pzIPv4, port: uPort, indexMdc: getUniqueIntKey(pzIPv4, uPort));
      clients[key] = client;
      client.connect();
      // 监听连接状态
      _subscriptions[key] = client.connectionStateStream.listen((connected) {
        connectionStateStream.add(MapEntry(key, connected));
      });
      // 监听数据接收
      _dataSubscriptions[key] = client.dataStream.listen((data) {
        dataStream.add(MapEntry(client.getIndexMdc(), data));
      });
    }
  }

  // 获取客户端
  SocketClient? getClient(String host, int port) {
    final key = '$host:$port';
    return clients[key];
  }

  // 获取客户端，根据索引_indexMdc
  SocketClient? getClientByIndex(int index) {
    for (final client in clients.values) {
      if (client.getIndexMdc() == index) {
        return client;
      }
    }
    return null;
  }

  // 断开所有客户端连接
  void disconnectAll() {
    for (final client in clients.values) {
      client.disconnect();
    }
    clients.clear();
    _subscriptions.clear();
    _dataSubscriptions.clear();
  }

  // 断开指定客户端连接
  void disconnectClient(String host, int port) {
    final key = '$host:$port';
    clients[key]?.disconnect();
    clients.remove(key);

    _subscriptions[key]?.cancel();
    _subscriptions.remove(key);

    _dataSubscriptions[key]?.cancel();
    _dataSubscriptions.remove(key);

    print('[SocketClientManager] $key disconnectClient ----->');
  }

  int getUniqueIntKey(String host, int port) {
    // 输入：192.168.9.42:6000 输出：9426000
    final String key = '$host$port'.replaceAll('.', '');
    final String ip = key.substring(key.length - 7);
    return int.parse(ip);
  }
}
